package com.niit.gams.controller;

import com.github.pagehelper.PageInfo;
import com.niit.gams.pojo.SysResource;
import com.niit.gams.pojo.TreeNode;
import com.niit.gams.service.SysResourceService;
import com.niit.gams.utils.TreeUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/resources")
public class SysResourceController {
  private SysResourceService sysResourceService;

  public SysResourceController(SysResourceService sysResourceService) {
    this.sysResourceService = sysResourceService;
  }
  @GetMapping
  public ResponseEntity<PageInfo<SysResource>> findResourceByPage(@RequestParam(defaultValue = "1") Integer curPage, @RequestParam(defaultValue = "2")Integer pageSize){
    PageInfo<SysResource> pageInfo = sysResourceService.findResourcesByPage(curPage, pageSize);
    return ResponseEntity.ok(pageInfo);
  }

  @PostMapping
  public ResponseEntity<Boolean> addPriv(SysResource resource){
     boolean flag = sysResourceService.addPriv(resource);
     return ResponseEntity.ok(flag);
  }

  @DeleteMapping("/{pid}")
  public ResponseEntity<Boolean> delPriv(@PathVariable("pid")Integer pid){
    boolean flag = sysResourceService.delPriv(pid);
    return ResponseEntity.ok(flag);
  }

  @GetMapping("/all")
  public ResponseEntity<List<TreeNode>> findAll(){
    List<SysResource> resources = sysResourceService.findAll();
    List<TreeNode> nodeList = new ArrayList<>();
    for (SysResource resource:resources) {
       TreeNode node = new TreeNode();
       node.setId(resource.getId());
       node.setName(resource.getName());
       node.setPId(resource.getParentId());
       nodeList.add(node);
    }
    return ResponseEntity.ok(nodeList);
  }
  @GetMapping("/pids/{rid}")
  public ResponseEntity<List<Long>> getAllPid(@PathVariable("rid") Long rid){
    List<Long> pids = sysResourceService.findPrivs(rid);
    return ResponseEntity.ok(pids);
  }

  @PutMapping
  public ResponseEntity<Boolean> updateRolePrivs(Long rid, @RequestParam("pids") List<Long> pids){
    boolean flag = sysResourceService.updateRolePrivs(rid,pids);
    return ResponseEntity.ok(flag);
  }

}
